package fi.bluepill.server.model;

import javax.persistence.Embeddable;

@Embeddable
public class LongLat {
    private static final Double R = 6371d;
    private Double longtitude;
    private Double latitude;

    public LongLat() {
    }

    public LongLat(Double longtitude, Double latitude) {
        this.longtitude = longtitude;
        this.latitude = latitude;
    }

    public Double getLongtitude() {
        return longtitude;
    }

    public Double getLatitude() {
        return latitude;
    }

    public Double distance(LongLat from) {
        double dLat = Math.toRadians(latitude - from.getLatitude());
        double dLon = Math.toRadians(longtitude - from.getLongtitude());

        double lat1 = Math.toRadians(latitude);
        double lat2 = Math.toRadians(from.getLatitude());

        double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c * 1000;
    }

    public Double bearing (LongLat from) {
        double dLat = Math.toRadians(latitude - from.getLatitude());
        double dLon = Math.toRadians(longtitude - from.getLongtitude());

        double lat1 = Math.toRadians(latitude);
        double lat2 = Math.toRadians(from.getLatitude());

        double y = Math.sin(dLon) * Math.cos(lat2);
        double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);

        return Math.toDegrees(Math.atan2(y, x));
    }

    public boolean closerThan(double meters, LongLat from) {
        if (distance(from) <= meters)
            return true;

        return false;
    }
}
